package bamin.com.bamindaijia.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.UILUtils;
import com.aiton.administrator.shane_library.shane.widget.MyCarDialog;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.Order;
import bamin.com.bamindaijia.model.Sms;
import cz.msebera.android.httpclient.Header;


public class OrderDetailActivity extends ZjbBaseActivity implements View.OnClickListener {

    private TextView mTv_time;
    private TextView mTv_state;
    private TextView mTv_start;
    private TextView mTv_end;
    private TextView mTv_finalprice;
    private TextView mTv_driverName;
    private TextView mTv_driveYear;
    private TextView mTv_orderNum;
    private ImageView mImg_order_driverImage;
    private SimpleRatingBar mRatingbar_pingfeng;
    private TextView mTv_pingjia;
    private LinearLayout mLine_pingjia;
    private LinearLayout mLine_no_pingjia;
    private TextView mTv_orderId;
    private RelativeLayout mRela_driver;
    private MyCarDialog mMyCarDialog;
    private TextView mTv_complain;
    private String mMode;
    private double mFee;
    private Order mData;
    private SimpleRatingBar mRatingbar_pingfeng_complete;
    private TextView mTv_pingjia_content;
    private EditText mEdt_pingjia;
    private TextView mTv_editNum;
    private SimpleRatingBar mRatingbar_pingfeng_driver;
    private TextView mTv_order_mileage;
    private TextView mTv_order_mileage_money;
    private TextView mTv_order_waiting_time;
    private TextView mTv_order_waiting_money;
    private TextView mTv_fee;
    private TextView mTv_comfirm_toll;
    private TextView mTv_order_other_money;
    private View include_price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        showLoadingDialog();
        init();
    }

    @Override
    protected void initData() {
    }


    @Override
    protected void initViews() {
        mTv_time.setText("下单时间：" + mData.getOrderTime());
        mTv_state.setText("订单状态：" + mData.getOrderStatus());
        mTv_start.setText(mData.getStartLocation());
        mTv_end.setText(mData.getEndLocation());
        mTv_orderId.setText("订单号：" + mData.getId());

        mTv_driverName.setText("司机：" + mData.getDriverName());
        mTv_driveYear.setText("驾龄：" + mData.getDriverDrivingTime());
        mTv_orderNum.setText("接单数：" + mData.getDriverOrderSum() + "单");


        mTv_order_mileage.setText("里程(" + mData.getMileage() + "公里)");
        Double mileageCost = mData.getMileageCost();
        mTv_order_mileage_money.setText(((mileageCost == null) ? 0 : mileageCost) + "元");


        Integer waitTime = mData.getWaitTime();
        mTv_order_waiting_time.setText("等待费用（" + (waitTime == null ? 0 : waitTime) + "分钟）");
        mTv_order_waiting_money.setText(mData.getWaitTimeFee() + "元");

        mTv_fee.setText(mData.getFee() + "元");

        Double tollFees = mData.getTollFees();
        mTv_comfirm_toll.setText((tollFees == null) ? 0 + "元" : tollFees + "元");

        mTv_order_other_money.setText(mData.getOtherFees() + "元");


        Double driverScore = mData.getDriverScore();
        double dScore = 5;
        if (driverScore != null) {
            dScore = driverScore;
        }

        mRatingbar_pingfeng_driver.setRating((float) dScore);
        String mImage = mData.getDriverImage();
        Log.e("checkLogin", "图片URL" + mImage);
        if (mImage != null && !TextUtils.isEmpty(mImage)) {
            ImageLoader.getInstance().clearDiskCache();
            UILUtils.displayImageNoAnim(mImage, mImg_order_driverImage);
        }
        Double finalPrice = mData.getFinalPrice();
        if (finalPrice != null) {
            mTv_finalprice.setText(finalPrice + "");
        } else {
            mTv_finalprice.setText(0 + "");
        }

        if (mData.getOrderStatus().equals("未评价")) {
            mLine_no_pingjia.setVisibility(View.VISIBLE);
            mLine_pingjia.setVisibility(View.GONE);
        } else if (mData.getOrderStatus().equals("完成")) {
            mLine_no_pingjia.setVisibility(View.GONE);
            mLine_pingjia.setVisibility(View.VISIBLE);
            Double score = mData.getScore();
            double s = 5;
            if (score != null) {
                s = score;
            }
            mRatingbar_pingfeng_complete.setRating((float) s);
            String comment = mData.getComment();
            if (comment != null) {
                if (!TextUtils.isEmpty(comment)) {
                    mTv_pingjia.setText(comment);
                } else {
                    mTv_pingjia.setText("无评价信息");
                }
            }
        } else {
            include_price.setVisibility(View.GONE);
            mLine_no_pingjia.setVisibility(View.GONE);
            mLine_pingjia.setVisibility(View.GONE);
        }
        cancelLoadingDialog();
    }
    @Override
    protected void setListeners() {
        findViewById(R.id.button_sure).setOnClickListener(this);
        mTv_complain.setOnClickListener(this);
        findViewById(R.id.imageView_back).setOnClickListener(this);
        mEdt_pingjia.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                mTv_editNum.setText("" + s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mMode = intent.getStringExtra(Constant.INTENT_KEY.TYPE);
        if (mMode.equals(Constant.TYPE.ALLORDER)) {
            mData = (Order) intent.getSerializableExtra(Constant.INTENT_KEY.ORDER_DETAIL);

        } else if (mMode.equals(Constant.TYPE.APPOINTEDORDER)) {
            mData = (Order) intent.getSerializableExtra(Constant.INTENT_KEY.ORDER_DETAIL);

        }

    }

    @Override
    protected void findID() {

        mTv_time = (TextView) findViewById(R.id.textView_time);
        mTv_complain = (TextView) findViewById(R.id.textView_complain);
        mTv_state = (TextView) findViewById(R.id.textView_OrderState);
        mTv_start = (TextView) findViewById(R.id.textView_start);
        mTv_end = (TextView) findViewById(R.id.textView_end);
        mTv_finalprice = (TextView) findViewById(R.id.textView_price);
        mTv_driverName = (TextView) findViewById(R.id.textView_driverName);
        mTv_driveYear = (TextView) findViewById(R.id.textView_driveYear);
        mTv_orderNum = (TextView) findViewById(R.id.textView_orderNum);
        mTv_pingjia = (TextView) findViewById(R.id.tv_pingjia_content);
        mTv_orderId = (TextView) findViewById(R.id.textView_orderId);
        mImg_order_driverImage = (ImageView) findViewById(R.id.img_order_driverImage);
        mRatingbar_pingfeng = (SimpleRatingBar) findViewById(R.id.ratingbar_pingfeng);
        mRatingbar_pingfeng_driver = (SimpleRatingBar) findViewById(R.id.ratingbar_pingfeng_driver);
        mRatingbar_pingfeng_complete = (SimpleRatingBar) findViewById(R.id.ratingbar_pingfeng_complete);
        mLine_no_pingjia = (LinearLayout) findViewById(R.id.line_no_pingjia);
        mLine_pingjia = (LinearLayout) findViewById(R.id.line_pingjia);
        mEdt_pingjia = (EditText) findViewById(R.id.edt_pingjia);
        mTv_editNum = (TextView) findViewById(R.id.tv_edittextNum);

        mTv_order_mileage = (TextView) findViewById(R.id.tv_order_mileage);
        mTv_order_mileage_money = (TextView) findViewById(R.id.tv_order_mileage_money);
        mTv_order_waiting_time = (TextView) findViewById(R.id.tv_order_waiting_time);
        mTv_order_waiting_money = (TextView) findViewById(R.id.tv_order_waiting_time_money);
        mTv_fee = (TextView) findViewById(R.id.textView_fee);
        mTv_comfirm_toll = (TextView) findViewById(R.id.tv_comfirm_toll);
        mTv_order_other_money = (TextView) findViewById(R.id.tv_order_other_money);

        include_price = findViewById(R.id.include_price);
//        mRela_driver = (RelativeLayout) findViewById(R.id.rela_driver);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();

        switch (v.getId()) {
//            case R.id.button_pinglun:
//                intent.setClass(this, PingJiaActivity.class);
//                intent.putExtra(Constant.INTENT_KEY.PINGJIA, Constant.INTENT_KEY.ORDER_DETAIL);
//                intent.putExtra(Constant.INTENT_KEY.DRIVER_INFO, driverDatas);
//                intent.putExtra(Constant.INTENT_KEY.ORDER, mData);
//                startActivityTo(intent);
//                break;
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.textView_complain:
                intent.setClass(this, ComplaintActivity.class);
//                intent.putExtra(Constant.INTENT_KEY.DRIVER_INFO, driverDatas);
                intent.putExtra(Constant.INTENT_KEY.ORDER, mData);
                startActivityTo(intent);
                break;
            case R.id.button_sure:
                pushPingjia();
                break;
        }
    }

    /**
     * 上传评价信息
     */
    private void pushPingjia() {
        showLoadingDialog();
        String url = Constant.Url.SET_PINGJIA;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("orderId", mData.getId());
        params.put("driverId", mData.getDriverId());
        params.put("score", mRatingbar_pingfeng.getRating() + "");
        params.put("comment", mEdt_pingjia.getText().toString().trim());
        Log.e("PingJiaActivity", "score: --->>" + mRatingbar_pingfeng.getRating());
        Log.e("PingJiaActivity", "comment: --->>" + mEdt_pingjia.getText().toString().trim());
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("PingJiaActivity", "评价返回" + s);
                try {
                    cancelLoadingDialog();
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    if (sms.getStatus() == 0) {

                        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(OrderDetailActivity.this, "评论上传成功", "确定");
                        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
                            @Override
                            public void doWhat() {
                                singleBtnDialog.dismiss();
                                setResult(Constant.REQUEST_RESULT_CODE.PINGJIA);
                                finishTo();
                            }
                        });
                        singleBtnDialog.show();

                        Toast.makeText(OrderDetailActivity.this, sms.getMes(), Toast.LENGTH_SHORT).show();


                    } else {
                        Toast.makeText(OrderDetailActivity.this, sms.getMes(), Toast.LENGTH_SHORT).show();

                    }
                } catch (Exception e) {
                    Toast.makeText(OrderDetailActivity.this, "评价失败,请检查网络", Toast.LENGTH_SHORT).show();
                    cancelLoadingDialog();

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("PingJiaActivity", "请求失败");
                Toast.makeText(OrderDetailActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                cancelLoadingDialog();

            }
        });
    }
}
